import 'package:auto_orientation/auto_orientation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';
import 'package:videodemo/z_video/assembly/zsn_bar.dart';
import 'package:videodemo/z_video/assembly/zsn_header.dart';
import 'package:videodemo/z_video/assembly/zsn_pause.dart';
import 'package:videodemo/z_video/assembly/zsn_progess.dart';
import 'package:videodemo/z_video/zsn_class.dart';
import 'package:videodemo/z_video/zsn_providers.dart';

class ZsnFullscreen extends StatefulWidget {
  final String title;
  final ZsnProviders providers;
  final VideoPlayerController controller;
  final Function() onTap;
  final Function() onDoubleTap;
  final Function() onLongPress;
  final Function() playVideo;
  final Function(dynamic) onVerticalDragUpdate;
  final Function(dynamic) onVerticalDragEnd;
  final Function(dynamic) onHorizontalDragUpdate;
  final Function(dynamic) onHorizontalDragEnd;
  final Function(dynamic) onLongPressEnd;
  const ZsnFullscreen({
    super.key,
    this.title = '',
    required this.providers,
    required this.controller,
    required this.onTap,
    required this.onDoubleTap,
    required this.onLongPress,
    required this.playVideo,
    required this.onVerticalDragUpdate,
    required this.onVerticalDragEnd,
    required this.onHorizontalDragUpdate,
    required this.onHorizontalDragEnd,
    required this.onLongPressEnd,
  });
  @override
  State<ZsnFullscreen> createState() => _SelfFullState();
}

class _SelfFullState extends State<ZsnFullscreen> {
  bool isLand = false; // 是否横屏

  @override
  void initState() {
    super.initState();

    // 通过视频比例确定是否需要全屏
    if (widget.controller.value.aspectRatio < 1) {
      // 竖屏模式
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
      AutoOrientation.portraitUpMode();
    } else {
      // 横屏模式
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
      AutoOrientation.landscapeRightMode();
      isLand = true;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // 全屏视频
        body: Consumer<ZsnProviders>(
      builder: (context, provider, child) {
        return GestureDetector(
          onTap: () {
            widget.onTap();
          },
          onDoubleTap: () {
            widget.onDoubleTap();
          },
          onLongPress: () {
            widget.onLongPress();
          },
          onLongPressEnd: (details) {
            widget.onLongPressEnd(details);
          },
          onVerticalDragUpdate: (details) {
            widget.onVerticalDragUpdate(details);
          },
          onVerticalDragEnd: (details) {
            widget.onVerticalDragEnd(details);
          },
          onHorizontalDragUpdate: (details) {
            widget.onHorizontalDragUpdate(details);
          },
          onHorizontalDragEnd: (details) {
            widget.onHorizontalDragEnd(details);
          },
          child: Container(
            color: Colors.black,
            child: Stack(
              children: <Widget>[
                Center(
                  child: provider.videoInitialized
                      ? Hero(
                          tag: 'player',
                          child: AspectRatio(
                            aspectRatio: widget.controller.value.aspectRatio,
                            child: VideoPlayer(widget.controller),
                          ))
                      : provider.errorMessage != null
                          ? Icon(
                              Icons.videocam_off_sharp,
                              color: Colors.red,
                              size: 45,
                            )
                          : CircularProgressIndicator(),
                ),
                // 顶部 UI
                if (provider.showUI && !provider.isLock)
                  ZsnHeader(
                    title: widget.title,
                    fullScreen: true,
                  ),
                // 暂停 UI
                if (provider.pause)
                  Center(
                      child: IconButton(
                          onPressed: () {
                            widget.playVideo();
                          },
                          icon: Icon(
                            Icons.play_arrow,
                            color: ZsnClass().baseColor,
                            size: 45,
                          ))),
                // 缓冲 UI
                if (provider.isBuffering)
                  Center(
                      child: CircularProgressIndicator(
                    backgroundColor: Colors.transparent,
                  )),
                // 快进快退 UI
                if (provider.second != 0)
                  Stack(
                    alignment: Alignment.center, // 这会将 Stack 的子内容居中
                    children: [
                      Positioned(
                        top: 40, // 垂直居中
                        child: Container(
                          // ignore: deprecated_member_use
                          color: Colors.black.withOpacity(0.2),
                          padding: EdgeInsets.symmetric(
                              horizontal: 10), // 可选，调整文字与容器边距
                          child: Text(
                            '${ZsnClass().formatDuration(provider.afterProgress)}/${ZsnClass().formatDuration(provider.videoDuration)}',
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                            textAlign: TextAlign.center, // 确保文字居中
                          ),
                        ),
                      ),
                    ],
                  ), // 音量 UI
                if (provider.volumeUI)
                  ZsnBar(
                      height: MediaQuery.of(context).size.height,
                      value: provider.currentVolume),
                // 亮度 UI
                if (provider.brightnessUI)
                  ZsnBar(
                    height: MediaQuery.of(context).size.height,
                    value: provider.currentBrightness,
                    isVolume: false,
                  ),
                // 底部控制条 UI
                if (provider.showUI && !provider.isLock)
                  Positioned(
                      bottom: 0,
                      left: 0,
                      child: Container(
                        padding: EdgeInsets.all(5),
                        width: MediaQuery.of(context).size.width,
                        // ignore: deprecated_member_use
                        color: Colors.black.withOpacity(0.1),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            // 上下居中
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              //  播放暂停按钮
                              ZsnPause(
                                  pause: provider.pause,
                                  playVideo: widget.playVideo),
                              // 播放进度
                              Text(
                                ZsnClass().formatDuration(
                                    provider.videoCurrentDuration),
                                style: TextStyle(color: Colors.white),
                              ),
                              SizedBox(
                                width: 10,
                              ),
                              // 进度条
                              ZsnProgess(controller: widget.controller),
                              SizedBox(
                                width: 10,
                              ),
                              // 播放进度
                              Text(
                                ZsnClass()
                                    .formatDuration(provider.videoDuration),
                                style: TextStyle(color: Colors.white),
                              ),
                              // 退出全屏按钮
                              IconButton(
                                icon: Icon(
                                  Icons.fullscreen_exit,
                                  color: Colors.white,
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ]),
                      )),
                // 锁屏按钮
                if (provider.showUI)
                  Positioned(
                      top: ZsnClass().calculateTopPosition(context),
                      left: 30,
                      child: IconButton(
                          style: ButtonStyle(
                            backgroundColor: WidgetStateProperty.all(
                                const Color.fromARGB(68, 158, 158, 158)),
                          ),
                          onPressed: () {
                            provider.changeLock();
                          },
                          icon: Icon(
                            provider.isLock ? Icons.lock : Icons.lock_open,
                            color: Colors.white,
                            size: 25,
                          ))),
              ],
            ),
          ),
        );
      },
    ));
  }

  @override
  void dispose() {
    if (isLand == true) {
      AutoOrientation.portraitUpMode();
    }
    // 恢复系统状态栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    super.dispose();
  }
}
